/*
 * @Author: “lichen”
 * @Date: 2023-06-07 11:56:59
 * @LastEditors: “lichen”
 * @LastEditTime: 2023-06-08 11:35:56
 * @Description: from https://juejin.cn/post/7237828040281276472
 */
import { useEffect, useRef, useState } from "react";
// import { imgArr as _imgArr } from "../mock";

const _mockData = [
    "https://img0.baidu.com/it/u=1797544775,2912350681&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800",
    "https://img1.baidu.com/it/u=2396404004,3078543528&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800",
    "https://img2.baidu.com/it/u=551125832,420285419&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
    "https://img1.baidu.com/it/u=1304255642,2961408783&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
];

export const Swiper = ({
    width = 600,
    height = 300,
    imgArr = _mockData,
}: any) => {
    const [renderItems, setRenderItems] = useState<any[]>([]);
    const [dataSource, setDataSource] = useState<
        {
            imgSrc: string;
            index: number;
        }[]
    >([]);
    /** 当前索引（用于切换页面） */
    const [currentIndex, setCurrentIndex] = useState<number>(0)
    /** 图片容器的Ref */
    const boxRef = useRef<HTMLDivElement | null>(null);
    /** 切换过程不允许被打断 */
    const changing = useRef<boolean>(false);

    /** 根据新的目标元素索引，更新图片渲染数组 */
    function updateRenderItems(targetIndex: number) {
        const _renderItems = [
            ...dataSource.slice(targetIndex),
            ...dataSource.slice(0, targetIndex),
        ];
        _renderItems.unshift(_renderItems[_renderItems.length - 1]);
        setRenderItems(_renderItems);
    }

    /** 切换到指定索引的图片 */
    function changeByIndex(targetIndex = 0, speed = 2   ) {
        if (!boxRef.current || changing.current || currentIndex === targetIndex) return;
        setCurrentIndex(targetIndex);
        changing.current = true;
        const boxEle = boxRef.current;
        let targeLeftPosition = 0;
        for (let i = 0; i < renderItems.length; i++) {
            if (renderItems[i].index === targetIndex) {
                targeLeftPosition = -width - (i - 1) * width;
                console.log(targeLeftPosition)
                break;
            }
        }
        let count = width;
        function changePage() {
            if (boxEle.style.left === `${targeLeftPosition}px`) {
                updateRenderItems(targetIndex);
                return requestAnimationFrame(() => {
                    boxEle.style.left = `-${width}px`;
                    changing.current = false;
                });
            }
            if (targeLeftPosition > -width) count -= width / (speed * 20);
            else count += width / (speed * 20);
            boxEle.style.left = `-${count}px`;
            requestAnimationFrame(changePage);
        }
        requestAnimationFrame(changePage);
    }
        
    useEffect(() => {
        const _imgArr = imgArr.map((item: string, index: number) => ({
            index,
            imgSrc: item,
        }));
        setDataSource(_imgArr);
        if (_imgArr.length > 1)
            setRenderItems([_imgArr[_imgArr.length - 1], ..._imgArr]);
        else setRenderItems([_imgArr[0], ..._imgArr, _imgArr[0]]);
    }, [imgArr]);
    return (
        <>
            <div
                style={{
                    width,
                    height,
                    position: "relative",
                    overflow: "hidden",
                }}
            >
                <div
                    style={{
                        position: "absolute",
                        left: -width,
                        display: "flex",
                    }}
                    ref={boxRef}
                >
                    {renderItems.map((item,index) => (
                        <div key={`${item.imgSrc}${index}`} style={{ width, height }}>
                            <img src={item.imgSrc} style={{ width: "100%", height }} alt="" />
                        </div>
                    ))}
                </div>
                <div style={{ position: 'absolute', width, height: 40, bottom: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', columnGap: 10 }}>
                    {
                        dataSource.map((_, index) => <div key={index} style={{ width: 10, height: 10, cursor: 'pointer', background: index === currentIndex ? '#2e8dff' : 'white', borderRadius: '50%' }} onClick={() => {
                            changeByIndex(index);
                        }}></div>)
                    }
                </div>
            </div>
            <button onClick={() => { changeByIndex((dataSource.length + currentIndex - 1) % dataSource.length); }}>上一页</button>
            <button onClick={() => { changeByIndex((currentIndex + 1) % dataSource.length); }}>下一页</button>
        </>
    );
};


